package com.rinlink.jbcodec.transform;


import com.rinlink.jbcodec.exception.TransformException;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class StringToBytes implements Transform<byte[]> {

    protected String str;
    protected int resultBytes;
    protected String charset;


    public StringToBytes(String str, int resultBytes, String charset) {
        this.str = str;
        this.charset = charset;
        this.resultBytes = resultBytes;
    }

    @Override
    public byte[] transform() {
        byte[] res = null;
        try {
            byte[] data = str.getBytes(charset);
            int bytes = Math.min(data.length,resultBytes);
            ByteBuffer buffer = ByteBuffer.allocate(resultBytes);
            buffer.put(str.getBytes(charset),0,bytes);
            res = buffer.array();
        } catch (UnsupportedEncodingException e) {
            String msg = String.format("无效的 `%s` 编码",charset);
            throw new TransformException(msg);
        }

        return res;
    }
}
